<template>
  <flexbox align="stretch">
    <flexbox-item style="margin-right: 50px;">
      <div class="area-title">定位</div>
      <el-autocomplete v-model="searchInput"
                       :fetch-suggestions="querySearchAsync"
                       style="width: 100%;"
                       placeholder="请输入详细位置名称"
                       @blur="inputBlur"
                       @focus="inputFocus"
                       @select="handleSelect">
        <template v-slot:default="{ item }">
          <div class="name">{{ item.address + item.title }}</div>
        </template>
      </el-autocomplete>
      <div ref="addressMap" class="map"/>
      <div class="area-title">详细地址</div>
      <el-input v-model="detailAddress" placeholder=""/>
    </flexbox-item>
    <flexbox-item>
      <div class="area-title">省/市/区</div>
      <v-distpicker :province="addressSelect.province" :city="addressSelect.city" :area="addressSelect.area"
                    @province="selectProvince" @city="selectCity" @area="selectArea"/>
    </flexbox-item>
  </flexbox>
</template>

<script setup>
import VDistpicker from '/src/szcomponent/VDistpicker/index.js'
import {getBaiduMap} from '/src/utils/index.js'

defineOptions({
  name: 'XhCustomerAddress', // 新建 客户位置
})

const props = defineProps({
  value: {
    type: Object,
    default: () => {
      return {}
    }
  },
  /** 索引值 用于更新数据 */
  index: Number,
  /** 包含数据源 */
  item: Object
})


const map = ref(null)
/** 搜索地图输入框 */
const searchInput = ref('')
const searchCopyInput = ref('') // 避免修改
/** 完整地址输入框 */
const detailAddress = ref('')
const pointAddress = ref(null) // 经纬度点
/** 区域选择 */
const addressSelect = ref({
  province: '',
  city: '',
  area: ''
})
/** 防止联动情况  */
const canExecute = ref(true)


watch(pointAddress, (newValue)=> {
  valueChange()
})
watch(detailAddress, (newValue)=> {
  valueChange()
})

onMounted(() => {
  getBaiduMap().then(() => {
    var map = new BMap.Map(cxt.refs.addressMap, {enableMapClick: false})
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 14)
    // map.disableDragging() //禁止拖拽
    // map.disableDoubleClickZoom()
    // map.disableScrollWheelZoom()
    // map.disableContinuousZoom()
    map.enableScrollWheelZoom()
    map.value = map
    if (props.value && JSON.stringify(props.value) !== '{}') {
      initInfo(props.value)
    } else {
      // 定位逻辑
      // var geolocation = new BMap.Geolocation()
      // var self = this
      // geolocation.getCurrentPosition(
      //   function(r) {
      //     if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      //       self.addMarkerLabel(r.point)
      //     }
      //   },
      //   { enableHighAccuracy: true }
      // )
    }
  }).catch(error => {
    console.log("error")
  })
})


function initInfo(val) {
  searchInput.value = val.location
  detailAddress.value = val.detailAddress
  if (Object.prototype.toString.call(val.address) == '[object Array]') {
    var address = {}
    for (let index = 0; index < val.address.length; index++) {
      index === 0 ? (address['province'] = val.address[0]) : ''
      index === 1 ? (address['city'] = val.address[1]) : ''
      index === 2 ? (address['area'] = val.address[2]) : ''
    }
    addressSelect.value = address
  }
  if (val.lng != 0 && val.lat != 0) {
    pointAddress.value = new BMap.Point(val.lng, val.lat)
    addMarkerLabel(pointAddress.value)
  }
}
function querySearchAsync(queryString, cb) {
  if (queryString) {
    var options = {
      onSearchComplete: function (results) {
        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
          var address = []
          for (var i = 0; i < results.getCurrentNumPois(); i++) {
            address.push(results.getPoi(i))
          }
          cb(address)
        } else {
          cb([])
        }
      },
      pageCapacity: 20
    }
    var local = new BMap.LocalSearch(map.value, options)
    local.search(queryString)
  } else {
    cb([])
  }
}
/** 搜索结果选择 */
function handleSelect(item) {
  searchInput.value = item.address + item.title
  searchCopyInput.value = searchInput.value // 只能通过这种方式修改

  detailAddress.value = searchInput.value
  addMarkerLabel(item.point)
  pointAddress.value = item.point
  mapSelectArea(item)
}
/** Input 失去焦点  searchInput 只能通过选择更改*/
function inputBlur() {
  if (searchCopyInput.value !== searchInput.value) {
    searchInput.value = searchCopyInput.value
  }
}
function inputFocus() {
  searchCopyInput.value = searchInput.value
}
// 创建标注
function addMarkerLabel(point) {
  map.value.clearOverlays()
  map.value.centerAndZoom(point, 14)
  map.value.addOverlay(new BMap.Marker(point))
}
/** 区域选择 */
function selectProvince(value) {
  addressSelect.value.province = value.value
  valueChange()
}
function selectCity(value) {
  addressSelect.value.city = value.value
  valueChange()
}
function selectArea(value) {
  addressSelect.value.area = value.value
  valueChange()
}
/** 地图选择区域 */
function mapSelectArea(data) {
  if (canExecute.value) {
    canExecute.value = false
    // this.addressSelect.province = data.province ? data.province : "";
    // this.addressSelect.city = data.city ? data.city : "";
    /** 因为poi里面不包含区域 所以需要逆地址解析 */
    var myGeo = new BMap.Geocoder()
    // 根据坐标得到地址描述
    var self = cxt
    myGeo.getLocation(
        new BMap.Point(data.point.lng, data.point.lat),
        function (result) {
          if (result) {
            // 获取经纬度点
            self.pointAddress = result.point
            self.addressSelect.province = result.addressComponents.province
                ? result.addressComponents.province
                : ''
            self.addressSelect.city = result.addressComponents.city
                ? result.addressComponents.city
                : ''
            self.addressSelect.area = result.addressComponents.district
                ? result.addressComponents.district
                : ''
          }
        }
    )

    setTimeout(() => {
      self.canExecute = true
    }, 500)
  }
}
// 值更新的回调
function valueChange() {
  emits('value-change', {
    index: props.index,
    value: {
      address: [
        addressSelect.value.province,
        addressSelect.value.city,
        addressSelect.value.area
      ],
      location: searchInput.value,
      detailAddress: detailAddress.value,
      lat: pointAddress.value ? pointAddress.value.lat : '',
      lng: pointAddress.value ? pointAddress.value.lng : ''
    }
  })
}


</script>


<script type="text/javascript">


export default {

  // components: {
  //   VDistpicker
  // },
  props: {},
  data() {
    return {}
  },
  computed: {},
  watch: {

  },
  mounted() {

  },
  methods: {

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.map {
  height: 150px;
  width: 100%;
  overflow: hidden;
  margin-top: 5px;
}

.area-title {
  font-size: 12px;
  color: #aaa;
  padding-left: 10px;
}
</style>
